package com.itheima.core.controller;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.itheima.core.pojo.product.Brand;
import com.itheima.core.pojo.product.Color;
import com.itheima.core.pojo.product.Product;
import com.itheima.core.pojo.product.Sku;
import com.itheima.core.service.CmsService;
import com.itheima.core.service.SearchService;

import cn.itcast.common.page.Pagination;

/**
 * @author zhang.cheng
 *
 *         2017年3月8日
 */
@Controller
public class ProductController {

	@Autowired
	private SearchService searchService;

	@Autowired
	private CmsService cmsService;

	@RequestMapping(value = "/")
	public String index() {
		return "index";
	}

	/**
	 * 搜索
	 * 
	 * @param pageNo
	 * @param keyword
	 * @param model
	 * @param price
	 * @param brandId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/search")
	public String search(Integer pageNo, String keyword, Model model, String price, Long brandId) throws Exception {
		// 从redis中查询品牌结果集
		List<Brand> brands = searchService.selectBrandListFromRedis();
		model.addAttribute("brands", brands);
		// 从solr中查询商品分页对象
		Pagination pagination = searchService.selectPaginationFromSolrByQuery(pageNo, keyword, price, brandId);
		model.addAttribute("pagination", pagination);
		model.addAttribute("keyword", keyword);
		model.addAttribute("price", price);
		model.addAttribute("brandId", brandId);

		// 创建map 存放已选条件的结果集
		Map<String, String> map = new HashMap<String, String>();
		if (null != brandId) {
			for (Brand brand : brands) {
				if (brand.getId().equals(brandId)) {
					map.put("品牌", brand.getName());
					break;
				}
			}
		}

		if (null != price) {
			if (price.contains("-")) {
				map.put("价格", price);
			} else {
				map.put("价格", price + "以上");
			}
		}

		model.addAttribute("map", map);

		return "search";
	}

	/**
	 * 去单品页
	 * 
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/product/detail")
	public String toProductDetail(Long id, Model model) {
		// 商品对象
		Product product = cmsService.toProductDetail(id);
		model.addAttribute("product", product);
		
		//图片
		String imgUrl = product.getImgUrl();
		String[] imgUrls = imgUrl.split(",");
		for (String img : imgUrls) {
			System.out.println(img);
		}
		model.addAttribute("imgUrls", imgUrls);
		
		// sku对象
		List<Sku> skus = cmsService.querySkuList(id);

		model.addAttribute("skus", skus);

		// 去掉颜色重复
		Set<Color> colors = new HashSet<Color>();
		for (Sku sku : skus) {
			colors.add(sku.getColor());
		}
		model.addAttribute("colors", colors);

		return "product";
	}
}
